<template>
  <div class="thumb-list-wrap">
    <div>
      <el-form :inline="true">
        <el-form-item label="关键字">
          <el-input
              v-model="queryParams.keywords"
              placeholder="文件夹名/对象名/标记词等关键字"
              clearable
              class="w-50 m-2"
              size="default"
              style="width: 300px;"
              :input-style="{height: '30px'}"
          />
        </el-form-item>
        <el-form-item>
          <el-button size="default" type="primary" class="ml10" @click="handleQuery">
            <el-icon>
              <ele-Search/>
            </el-icon>
            查询
          </el-button>
          <el-dropdown @command="handleNewObjectCommand" style="margin-left: 10px;">
            <el-button type="success">
              <el-icon>
                <ele-Plus/>
              </el-icon>
              新建
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="folder">新建文件夹</el-dropdown-item>
                <el-dropdown-item command="upload">上传文件</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>
      </el-form>
    </div>
    <div class="list-wrap" v-if="list.length > 0">
      <el-table :data="list" style="width: 100%">
        <el-table-column label="对象名称" width="400" show-overflow-tooltip>
          <template #default="scope">
            <div class="title-wrap" @click="goDirectory(scope.row)"
                 @contextmenu="handleGroupRightMenus(scope.row, $event)">
              <el-image v-if="scope.row.type == 'folder'" :src="FolderIcon"/>
              <el-image v-else-if="scope.row.type == 'docx'" :src="WordIcon"/>
              <el-image v-else-if="scope.row.type == 'excel'" :src="ExcelIcon"/>
              <el-image v-else-if="scope.row.type == 'ppt'" :src="PptIcon"/>
              <el-image v-else-if="scope.row.type == 'pdf'" :src="PdfIcon"/>
              <el-image v-else-if="scope.row.type == 'audio'" :src="AudioIcon"/>
              <el-image v-else-if="scope.row.type == 'video'" :src="VideoIcon"/>
              <el-image v-else-if="scope.row.type == 'android'" :src="AndriodIcon"/>
              <el-image v-else-if="scope.row.type == 'java'" :src="JarIcon"/>
              <el-image v-else-if="scope.row.type == 'photo'" :src="PictureIcon"/>
              <el-image v-else-if="scope.row.type == 'txt'" :src="TxtIcon"/>
              <el-image v-else :src="UnknowIcon"/>
              <span>
            {{ scope.row.name }}
          </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="存储类别">
          <template #default="scope">
            {{ source == 'local' ? '本地存储' : '云存储' }}
          </template>
        </el-table-column>
        <el-table-column label="对象类型">
          <template #default="scope">
            {{ scope.row.type }}
          </template>
        </el-table-column>
        <el-table-column label="Mime Type" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.mimeType }}
          </template>
        </el-table-column>
        <el-table-column label="对象大小">
          <template #default="scope">
            {{ scope.row?.size ? scope.row?.size : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template #default="scope">
            {{ scope.row.createdAt }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <div class="color-primary" @contextmenu="handleGroupRightMenus(scope.row, $event)">右键操作</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-else>
      <EmptyData/>
    </div>
    <context-menu
        v-model:show="showRightMenu"
        :options="contextMenuOptions"
    >
      <template v-if="currentRow.type == 'folder'">
        <context-menu-item icon="" @click="handleDirEdit(currentRow)"
                           style="justify-content: flex-start;display: flex;flex-direction: column-reverse;">
          <el-icon style="margin-right: 20px;">
            <ele-EditPen/>
          </el-icon>
          重命名
        </context-menu-item>
      </template>
      <template v-else>
        <context-menu-item icon="" @click="handleRemark(currentRow.id, currentRow.type == 'folder' ? 'folder' : 'file')"
                           style="justify-content: flex-start;display: flex;flex-direction: column-reverse;">
          <el-icon style="margin-right: 20px;">
            <ele-EditPen/>
          </el-icon>
          备注对象
        </context-menu-item>
      </template>
      <context-menu-item @click="handleDetail(currentRow.id, currentRow.type == 'folder' ? 'folder' : 'file')"
                         style="justify-content: flex-start;display: flex;flex-direction: column-reverse;">
        <el-icon style="margin-right: 20px;">
          <ele-Warning/>
        </el-icon>
        详情信息
      </context-menu-item>
      <template v-if="currentRow.type != 'folder'">
        <context-menu-item @click="copyText(currentRow.src)"
                           style="justify-content: flex-start;display: flex;flex-direction: column-reverse;">
          <el-icon style="margin-right: 20px;">
            <ele-Link/>
          </el-icon>
          复制链接
        </context-menu-item>
        <context-menu-item @click="handleImageDownload(currentRow.bigSrc)"
                           style="justify-content: flex-start;display: flex;flex-direction: column-reverse;">
          <el-icon style="margin-right: 20px;">
            <ele-Download/>
          </el-icon>
          下载文件
        </context-menu-item>
      </template>
      <context-menu-item @click="handleMove"
                         style="justify-content: flex-start;display: flex;flex-direction: column-reverse;">
        <el-icon style="margin-right: 20px;">
          <ele-Right/>
        </el-icon>
        移动对象
      </context-menu-item>
      <context-menu-item @click="handleShare(currentRow.id)"
                         style="justify-content: flex-start;display: flex;flex-direction: column-reverse;">
        <el-icon style="margin-right: 20px;">
          <ele-Share/>
        </el-icon>
        分享对象
      </context-menu-item>
      <context-menu-sperator/>
      <context-menu-item @click="handleDelete"
                         style="justify-content: flex-start;display: flex;flex-direction: column-reverse;">
        <el-icon style="margin-right: 20px;">
          <ele-Delete/>
        </el-icon>
        删除对象
      </context-menu-item>
    </context-menu>
    <ItemDetail ref="itemDetailRef"/>
    <DirectoryEdit ref="directoryEditRef" @callback="refreshList"/>
    <MoveToDirectory ref="moveToDirectoryRef" @callback="refreshList"/>
    <DirectoryAdd ref="directoryAddRef" @callback="refreshList"/>
    <ObjectUpload ref="objectUploadRef" @callback="refreshList"/>
    <RemarkFile ref="remarkFileRef" @callback="refreshList"/>
  </div>
</template>

<script lang="ts">
import {reactive, toRefs, defineComponent, ref} from 'vue';

import FolderIcon from '/@/assets/attach/folder_icon.svg';
import WordIcon from '/@/assets/attach/word_icon.png';
import ExcelIcon from '/@/assets/attach/excel_icon.png';
import TxtIcon from '/@/assets/attach/txt_icon.png';
import PptIcon from '/@/assets/attach/ppt_icon.png';
import PdfIcon from '/@/assets/attach/pdf_icon.png';
import AudioIcon from '/@/assets/attach/audio_icon.png';
import VideoIcon from '/@/assets/attach/video_icon.png';
import AndriodIcon from '/@/assets/attach/android_icon.svg';
import JarIcon from '/@/assets/attach/jar_icon.png';
import UnknowIcon from '/@/assets/attach/unkonw_icon.png';
import PictureIcon from '/@/assets/attach/picture_icon.svg';
import commonFunction from "/@/utils/commonFunction";
import ItemDetail from "/@/views/attachment/local/component/itemDetail.vue";
import DirectoryEdit from "/@/views/attachment/local/component/directoryEdit.vue";
import MoveToDirectory from "/@/views/attachment/local/component/moveToDirectory.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {deleteDirectory, deleteFile} from "/@/api/attachment";
import ObjectUpload from "/@/views/attachment/local/component/objectUpload.vue";
import DirectoryAdd from "/@/views/attachment/local/component/directoryAdd.vue";
import EmptyData from "/@/components/common/emptyData.vue";
import RemarkFile from "/@/views/attachment/local/component/remarkFile.vue";

export default defineComponent({
  name: 'attachmentDirectoryItemList',
  components: {
    EmptyData, DirectoryAdd, ObjectUpload,
    ItemDetail, DirectoryEdit, MoveToDirectory, RemarkFile
  },
  props: {
    list: {
      type: Array<Object>,
      default: () => [],
    },
    source: {
      type: String,
      default: () => 'local',
    },
    folder: {
      type: Object,
      default: () => {
        return {
          directoryId: 0,
          directoryName: ''
        }
      },
    }
  },
  setup(props, {emit}) {
    const directoryAddRef = ref();
    const objectUploadRef = ref();
    const {copyText} = commonFunction();
    const itemDetailRef = ref();
    const directoryEditRef = ref();
    const remarkFileRef = ref();
    const moveToDirectoryRef = ref();
    const acType = ref('add')
    const state = reactive({
      showRightMenu: false,
      queryParams: {
        keywords: ""
      },
      contextMenuOptions: {
        theme: '',
        zIndex: 3,
        minWidth: 110,
        x: 500,
        y: 200
      },
      currentRow: {
        id: 0,
        type: '',
        name: '根目录'
      }
    });
    const goDirectory = (detail: any) => {
      if (detail.type == 'folder') {
        emit('goDirectory', detail);
      }
      if (['excel', 'pdf', 'docx', 'ppt', 'pptx'].includes(detail.type)) {
        emit('previewFile', detail);
      }
      if (detail.type == 'photo') {
        emit('showGallery', detail.src);
      }
    };
    const handleDirEdit = (_row: any) => {
      directoryEditRef.value.openDialog(_row);
    };
    const handleDetail = (_id: number, _type: string) => {
      //
      itemDetailRef.value.openDialog(_id, _type);
    };
    const handleRemark = (_id: number, _type: string) => {
      if (_type != 'folder') {
        remarkFileRef.value.openDialog({
          id: _id,
          fullName: state.currentRow.name,
        });
      }
    };
    const handleMove = () => {
      const _row = {
        id: state.currentRow.id,
        source: props.source,
        type: state.currentRow.type == 'folder' ? 'folder' : 'file',
      };
      moveToDirectoryRef.value.openDialog(_row);
    };
    const handleShare = (_id: number) => {
      //
    };
    const handleDelete = () => {
      const _str = state.currentRow.type == 'folder' ? '文件夹' : '对象文件'
      ElMessageBox.confirm(`此操作将永久删除${_str}：“${state.currentRow.name}”, 是否继续?`, '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            if (state.currentRow.type == 'folder') {
              deleteDirectory({id: state.currentRow.id}).then(res => {
                ElMessage.success(`删除${_str}成功`);
                emit("callback");
              })
            } else {
              deleteFile({id: state.currentRow.id}).then(res => {
                ElMessage.success(`删除${_str}成功`);
                emit("callback");
              })
            }
          })
          .catch(() => {
          });
    };
    const refreshList = () => {
      emit("callback");
    };
    const handleImageDownload = (_src: any) => {
      let image = new Image()
      image.setAttribute('crossOrigin', 'anonymous')
      let names = 'image' + _src.split('/').pop()
      image.src = _src
      image.onload = function () {
        let canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        let context = canvas.getContext('2d')
        if (context != null) {
          context.drawImage(image, 0, 0, image.width, image.height)
          let url = canvas.toDataURL('image/jpeg') //得到图片的base64编码数据
          let a = document.createElement('a') // 生成一个a元素
          let event = new MouseEvent('click') // 创建一个单击事件
          a.download = names || 'photo' // 设置图片名称
          a.href = url // 将生成的URL设置为a.href属性
          a.dispatchEvent(event) // 触发a的单击事件
        }
      }
      image.src = _src
    };
    const handleGroupRightMenus = (_row: any, event: MouseEvent) => {
      event.preventDefault();
      state.currentRow = _row
      state.showRightMenu = true;
      state.contextMenuOptions.x = event.x;
      state.contextMenuOptions.y = event.y;
    };

    const handleNewObjectCommand = (_cmd: string) => {
      if (_cmd == 'folder') {
        // 新建文件夹
        let _data = props.folder;
        _data.tag = props.source == 'hwobs' ? 'cloudOnly' : '';
        directoryAddRef.value.openDialog(_data);
      }
      if (_cmd == 'upload') {
        // 上传文件
        objectUploadRef.value.openDialog(props.folder, props.source);
      }
    };
    const handleQuery = () => {
      let _folder = props.folder;
      _folder.folderId = _folder.directoryId;
      _folder.folderName = _folder.directoryName;
      _folder.keywords = state.queryParams.keywords;
      emit('goDirectory', _folder);
    };
    return {
      directoryAddRef,
      objectUploadRef,
      itemDetailRef,
      directoryEditRef,
      moveToDirectoryRef,
      remarkFileRef,
      FolderIcon,
      WordIcon,
      ExcelIcon,
      TxtIcon,
      PptIcon,
      PdfIcon,
      AudioIcon,
      VideoIcon,
      PictureIcon,
      AndriodIcon,
      JarIcon,
      UnknowIcon,
      acType,
      ...toRefs(state),
      copyText,
      goDirectory,
      handleDirEdit,
      handleRemark,
      handleDetail,
      handleMove,
      handleShare,
      handleDelete,
      handleGroupRightMenus,
      handleImageDownload,
      refreshList,
      handleNewObjectCommand,
      handleQuery,
    };
  },
});
</script>
<style lang="scss" scoped>
.list-wrap {
  .content-wrap {
    width: 100%;
    height: 100%;
    padding: 15px 10px 10px 10px;
    border-radius: 8px;
  }

  .title-wrap {
    display: flex;
    align-items: center;
    cursor: pointer;

    .el-image {
      width: 20px;
      height: 20px;
      display: block;
      border-radius: 5px;
      margin-right: 6px;

      img {
        width: 20px;
        height: 20px;
        border-radius: 10px;
      }
    }

    span {
      white-space: nowrap;
      text-overflow: ellipsis;
      color: #2196f3;
      font-size: 13px;
      width: 440px;
    }
  }


  p {
    text-align: center;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    padding-top: 6px;
  }

  &:hover {
    background-color: #efefef;
  }
}
</style>
